﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

namespace HotUI{
	public enum ePrestrainDataType{
		GameObject,
	}
	public struct PrestrainData{
		public ePrestrainDataType assetDataType;
		public string name;
		public string path;
		public PrestrainData(ePrestrainDataType _type,string _name){
			assetDataType = _type;
			name = _name;
			path = "";
		}
		public PrestrainData(ePrestrainDataType _type,string _name,string _path){
			assetDataType = _type;
			name = _name;
			path = _path;
		}
		public void Load(){
			GameTool.PrestrainLoad(this);
		}
	}

	public class PrestrainCtrl{
		public List<PrestrainData> pdata = new List<PrestrainData>();
		System.Action<float> callback;
		System.Action finish;
		int current;
		public void AddPrestrain(ePrestrainDataType type,string name){
			pdata.Add(new PrestrainData(type,name));
		}
		public void ReadyToPrestraining(System.Action<float> _callback,System.Action _finish){
			callback = _callback;
			finish = _finish;
		}
		public void Update(){
			if(current >= pdata.Count)
				Finish();
			else{
				pdata[current].Load();
				current++;
				callback((float)current/pdata.Count);
			}
		}
		void Finish(){
			callback(1);
			finish();
		}
	}

	public class BaseSceneCtrl:MyLuaBehaviour {
		public bool sleep;
		public bool prestraining;
		PrestrainCtrl prestrainCtrl = new PrestrainCtrl();
		LuaView loadview;

		public void TestCall(){
			Debug.Log("!!!!!!!!!!!!!!!!!!!!!!!!");
		}
		public void Update(){
			if (!sleep) {
				if (UIMgr.Instance.isInited && loadLuaFinish) {
					sleep = true;
					OnBegin ();
				}
			} else {
				OnUpdate ();
			}
		}

		protected virtual void OnBegin(){
			ShowUI ();
			BeginPrestrain ();
			if(loadLuaState == enLoadLuaState.HasLua){
				CallLua("BeginPrestrain");
			}
			Prestraining();
		}

		void ShowUI(){
			loadview = UIMgr.Instance.SetState ("loading","");	
		}

		protected virtual void BeginPrestrain(){
			
		}
		protected void Prestraining(){
			prestraining = true;
			prestrainCtrl.ReadyToPrestraining(SetSlider,PrestrainFinish);
		}

		protected virtual void OnUpdate(){
			if(prestraining){
				prestrainCtrl.Update();
			}
		}
		void PrestrainFinish(){
			prestraining = false;
			Debug.Log("---------------------预加载完毕------------");
			loadview.Close();
			CallLua("PrestrainFinish");
		}
		void SetSlider(float value){
			if (loadview != null) {
				loadview.DoCommand (new LVC_UpdateSlider ("Slider", value));
			}
		}
		
		#region LuaCall
		public void AddPrestrainData(int type,string name){
			prestrainCtrl.AddPrestrain((ePrestrainDataType)type,name);
		}
		#endregion
	}
}